﻿/*******************************************************************************
 * CreateTime:2022-04-04 11:37:42
 * Description: YoursLC有源低代码
*********************************************************************************/

using System;
using System.Data;
using System.Collections.Generic;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;
using Think9.Services.Table;
using Think9.Services.Flow;

namespace Think9.Services.CodeBuild
{
	/// <summary>
	/// 主表Service
	/// </summary>
	public class Demo21Service : BaseService<Demo21Model>
	{
		private ComService ComService = new ComService();
		private string split = BaseUtil.ComSplit;//字符分割 用于多选项的分割等 如split+选项1+split+选项2+split
		private string sql;

		//添加前数据处理
		public int BeforeAdd(ref string err, CurrentUserEntity CurrentUser, CurrentPrcsEntity mPrcs, string flowid, string maintbid, string tbname)
		{
			int listid = 0;

			//处理自动编号-- 如果有则添加一条数据,返回自增长的listid;如果没有则返回0
			listid = AutoNo.SetAutoNumber(ref err, CurrentUser, mPrcs, flowid, tbname);

			//处理子表数据初始化 首先主表添加一条空数据
			if (listid == 0)
			{
				listid = PageCom.InsertEmptyReturnID(ref err, maintbid, flowid, tbname, CurrentUser, mPrcs);
			}
			
			SubTable21Service SubTable21Service = new SubTable21Service();
			SubTable21Service.GridDataInit(listid);
			Record.AddRecord("system", listid.ToString(), flowid, "子表数据初始化");

			return listid;
		}

		//编辑后数据处理
		public string AfterEdit(string listid, string flowid, string prcsid, CurrentUserEntity user)
        {
			string err = "";

			//调用通用函数实现数据回写，用户可自定义 数据回写在录入表管理/数据读写中设置
			WriteBack WriteBack = new WriteBack();
			string maintbid = flowid.Replace("bi_", "tb_").Replace("fw_", "tb_");
			err = WriteBack.WriteValueByRelationSet(listid, flowid, maintbid, prcsid, user);

			return err;
		}

		//完成后数据处理
		public string AfterFinish(string listid, string flowid, string prcsid, CurrentUserEntity user)
		{
			string err = AfterEdit(listid, flowid, prcsid, user);
			if(string.IsNullOrEmpty(err))
            {
				//数据锁定等
				FlowCom.FinishFlowPrcs(listid, flowid, prcsid, user);
            }

			return err;
		}

		/// <summary>
		/// 主表查询调用 返回列表 查询条件可在录入表指标属性中设置
		/// </summary>
		/// <param name="total"></param>
		/// <param name="model"></param>
		/// <param name="pageInfo"></param>
		/// <param name="user"></param>
		/// <param name="flowid"></param>
		/// <param name="tbid"></param>
		/// <returns></returns>
		public IEnumerable<dynamic> GetPageListBySearch(ref long total, Demo21Model model, PageInfoEntity pageInfo, CurrentUserEntity user, string flowid, string tbid)
		{
			string where = BasicHelp.GetWhereByFlowId(user, flowid);

			//员工编码
			if (!string.IsNullOrEmpty(model.inEmployeeCode))
			{
				where += " and (tb_Demo21.inEmployeeCode = @inEmployeeCode)"; 
			}
			//员工部门
			if (!string.IsNullOrEmpty(model.inEmployeeDepartment))
			{
				where += " and (tb_Demo21.inEmployeeDepartment like @inEmployeeDepartment)"; 
				model.inEmployeeDepartment = string.Format("%{0}%", model.inEmployeeDepartment); 
			}
			//员工姓名
			if (!string.IsNullOrEmpty(model.inEmployeeName))
			{
				where += " and (tb_Demo21.inEmployeeName like @inEmployeeName)"; 
				model.inEmployeeName = string.Format("%{0}%", model.inEmployeeName); 
			}
			//员工岗位
			if (!string.IsNullOrEmpty(model.inEmployeePosition))
			{
				where += " and (tb_Demo21.inEmployeePosition like @inEmployeePosition)"; 
				model.inEmployeePosition = string.Format("%{0}%", model.inEmployeePosition); 
			}
			//编码
			if (!string.IsNullOrEmpty(model.inCode))
			{
				where += " and (tb_Demo21.inCode like @inCode)"; 
				model.inCode = string.Format("%{0}%", model.inCode); 
			}
			//名称
			if (!string.IsNullOrEmpty(model.inName))
			{
				where += " and (tb_Demo21.inName like @inName)"; 
				model.inName = string.Format("%{0}%", model.inName); 
			}
			//名称2
			if (!string.IsNullOrEmpty(model.inName2))
			{
				where += " and (tb_Demo21.inName2 like @inName2)"; 
				model.inName2 = string.Format("%{0}%", model.inName2); 
			}
			//小数1
			if(model.inDecimal1 != null)
			{
				where += " and (tb_Demo21.inDecimal1 >= @inDecimal1)"; 
			}
			if(model.inDecimal1_Exa  != null)
			{
				where += " and (tb_Demo21.inDecimal1 <= @inDecimal1_Exa)"; 
			}
			return base.GetPageByFilter(ref total, model, pageInfo, where);

		}

		/// <summary>
		/// 主表 为下拉选择、多选、单选准备动态数据源
		/// 负责列表显示时value与text转化 动态数据源来源于为指标指定的数据规范
		/// </summary>
		/// <param name="from"></param>
		/// <param name="param"></param>
		/// <returns></returns>
		public IEnumerable<valueTextEntity> GetSelectList(string from, object param)
		{
			DataTable dt = DataTableHelp.NewValueTextDt();

			//员工编码
			sql = "select inEmployeeCode as id,inEmployeeName as name FROM tb_Data03 ORDER BY inEmployeeCode";
			foreach (DataRow dr in ComService.GetDataTable(sql, param).Rows)
			{
				DataRow row = dt.NewRow();
				row["ClassID"] = "inEmployeeCode";
				row["Value"] = dr["id"].ToString();
				row["Text"] = dr["name"].ToString();
				dt.Rows.Add(row);
			}

			//DataTable转换成IEnumerable
			return DataTableHelp.ToEnumerable<valueTextEntity>(dt);
		}

		/// <summary>
		/// 弹出页面的查询条件有下拉选择、多选、单选时，为其绑定动态数据源
		/// 动态数据源来源于为指标指定的数据规范
		/// </summary>
		/// <param name="tbid"></param>
		/// <param name="indexid"></param>
		/// <param name="from"></param>
		/// <param name="param"></param>
		/// <returns></returns>
		public IEnumerable<valueTextEntity> GetSelectList(string tbid, string indexid, string from, object param)
		{
			DataTable dt = DataTableHelp.NewValueTextDt();

			//主表指标弹出页面
			if (tbid == "_main")
			{
				if (indexid == "inCode")
				{
					sql = "select DetailName as id,DetailName as name FROM sys_itemsdetail where ItemCode = 'Company' ORDER BY OrderNo";
					foreach (DataRow dr in ComService.GetDataTable(sql).Rows)
					{
						DataRow row = dt.NewRow();
						row["ClassID"] = "inName2";
						row["Value"] = dr["id"].ToString();
						row["Text"] = dr["name"].ToString();
						dt.Rows.Add(row);
					}
				}
			}
			else//子表指标弹出页面
			{
				if (indexid == "SubTable21v1")
				{
					sql = "select DetailName as id,DetailName as name FROM sys_itemsdetail where ItemCode = 'Department' ORDER BY OrderNo";
					foreach (DataRow dr in ComService.GetDataTable(sql).Rows)
					{
						DataRow row = dt.NewRow();
						row["ClassID"] = "inEmployeeDepartment";
						row["Value"] = dr["id"].ToString();
						row["Text"] = dr["name"].ToString();
						dt.Rows.Add(row);
					}
					sql = "select DetailName as id,DetailName as name FROM sys_itemsdetail where ItemCode = 'Post' ORDER BY OrderNo";
					foreach (DataRow dr in ComService.GetDataTable(sql).Rows)
					{
						DataRow row = dt.NewRow();
						row["ClassID"] = "inEmployeePosition";
						row["Value"] = dr["id"].ToString();
						row["Text"] = dr["name"].ToString();
						dt.Rows.Add(row);
					}
				}
			}

			//DataTable转换成IEnumerable
			return DataTableHelp.ToEnumerable<valueTextEntity>(dt);
		}

		/// <summary>
		/// 数据删除
		/// </summary>
		/// <param name="id"></param>
		/// <param name="fwid"></param>
		/// <returns></returns>
		public bool DeleteByID(string id, string fwid)
		{
			//删除子表数据
			ComService.ExecuteSql("delete from tb_SubTable21 where ListId=" + id + "");
			AttachmentService.DelAttachment(int.Parse(id), fwid);//删除附件 要最先执行
			//删除flowrunlist、flowrunprcslist中关联数据
			if (fwid.StartsWith("fw_"))
			{
				ComService.ExecuteSql("delete from flowrunlist where ListId = " + id + "");
				ComService.ExecuteSql("delete from flowrunprcslist where ListId = " + id + "");
			}

			AutoNo.DelAutoNo(id, fwid);//删除自动编号

			return base.DeleteByWhere("where ListId=" + id + "");//删除主表数据
		}

		/// <summary>
		///返回可修改字段 自由流程排除了隐藏指标 固定流程排除了隐藏指标及不可写字段
		/// </summary>
		/// <param name="prcno"></param>
		/// <returns></returns>
		public string GetUpdateFields(string prcno)
		{
			//自由流程或无流程排除了隐藏指标
			 return "inEmployeeCode,inEmployeeDepartment,inEmployeeName,inEmployeePosition,inCode,inName,inName2,inDecimal1";
		}
		
		//主表计算式
		public void ReadValue(ref List<ControlEntity> list, CurrentUserEntity user, IEnumerable<ControlEntity> controlslist, string tbid, string indexid, string value)
		{
			string tbname = "";
			string some = "";
			string where = "";
			string order = "";
			
			if (indexid == "inEmployeeCode")
			{
				//读取员工信息
				tbname = "tb_data03";
				some = "inEmployeeCode AS inEmployeeCode,inEmployeeDepartment AS inEmployeeDepartment,inEmployeeName AS inEmployeeName,inEmployeePosition AS inEmployeePosition";
				where = "where tb_data03.inemployeecode = @inEmployeeCode";
				order = " order by listid";
				object param = new { inEmployeeCode = value };
				
				DataTable dt = ComService.GetDataTable(tbname, some, where, order, param);
				if (dt.Rows.Count > 0)
				{
					//员工编码
					list.Add(new ControlEntity { ControlID = "inEmployeeCode", ControlValue = dt.Rows[0]["inEmployeeCode"].ToString(), ControlType = "2" });
					
					//员工部门
					list.Add(new ControlEntity { ControlID = "inEmployeeDepartment", ControlValue = dt.Rows[0]["inEmployeeDepartment"].ToString(), ControlType = "1" });
					
					//员工姓名
					list.Add(new ControlEntity { ControlID = "inEmployeeName", ControlValue = dt.Rows[0]["inEmployeeName"].ToString(), ControlType = "1" });
					
					//员工岗位
					list.Add(new ControlEntity { ControlID = "inEmployeePosition", ControlValue = dt.Rows[0]["inEmployeePosition"].ToString(), ControlType = "1" });
					
				}
			}
			
			if (indexid == "inCode")
			{
				//读取数据
				tbname = "tb_data07";
				some = "inCode AS inCode,inDecimal1 AS inDecimal1,inName AS inName,inName2 AS inName2";
				where = "where tb_data07.incode = @inCode";
				order = " order by listid";
				object param = new { inCode = value };
				
				DataTable dt = ComService.GetDataTable(tbname, some, where, order, param);
				if (dt.Rows.Count > 0)
				{
					//编码
					list.Add(new ControlEntity { ControlID = "inCode", ControlValue = dt.Rows[0]["inCode"].ToString(), ControlType = "1" });
					
					//小数1
					list.Add(new ControlEntity { ControlID = "inDecimal1", ControlValue = dt.Rows[0]["inDecimal1"].ToString(), ControlType = "1" });
					
					//名称
					list.Add(new ControlEntity { ControlID = "inName", ControlValue = dt.Rows[0]["inName"].ToString(), ControlType = "1" });
					
					//名称2
					list.Add(new ControlEntity { ControlID = "inName2", ControlValue = dt.Rows[0]["inName2"].ToString(), ControlType = "1" });
					
				}
			}
			
		}

	}
}